package com.hxalex.simulationhandle.accessbilityService.manger;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import com.hxalex.simulationhandle.R;
import com.hxalex.simulationhandle.accessbilityService.receiver.search.SearchBaiduInfoReceiver;
import com.hxalex.simulationhandle.ui.home.model.KeyWordBean;
import com.hxalex.simulationhandle.ui.home.model.WebSiteBean;
import com.hxalex.simulationhandle.util.SystemALertDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by hx_Alex on 2018/5/30.
 */

public class SearchManger {
    public  static final  String OPEN_WAKE_WINWODS="OPEN_WAKE_WINWODS";
    private static String TAG = "SearchManger";
    private static SearchManger searchManger;
    private static Context context;
    private  List<KeyWordBean> loadKeyWordData;//加载的关键词->循环执行当前任务是要从这两个bean里面拿数据给keyWordData，webSiteData
    private  List<WebSiteBean> loadWebSiteData;//加载的网站库
    private List<KeyWordBean> keyWordData;//关键词
    private List<WebSiteBean> webSiteData;//网站库
    private AccessibilityNodeInfo btn_search = null;
    private AccessibilityNodeInfo edit_search = null;
    private List<AccessibilityNodeInfo> contentMatchList = new ArrayList<>();
    private List<AccessibilityNodeInfo> oldContentMatchList = new ArrayList<>();
    private int webSiteStopTime = 0;
    private int taskLoopNum=0;
    private int nowTaskLoopNum=0;
    private SearchManger(Context context) {
        this.context = context;
        EventBus.getDefault().register(this);
    }


    public synchronized static SearchManger getSearchManger(Context context) {
        SearchManger.context = context;
        if (searchManger == null) {
                searchManger = new SearchManger(context);
        }
        return searchManger;
    }

    public static SearchManger getNewSearchManger(Context context, List<KeyWordBean> keyWordData, List<WebSiteBean> webSiteData,List<KeyWordBean> loadkeyWordData, List<WebSiteBean> loadwebSiteData, int webSiteStopTime,int taskLoopNum,int nowTaskLoopNum) {
        SearchManger.context = context;
        if (searchManger == null) {
            synchronized (SearchManger.class) {
                searchManger = new SearchManger(context);
                searchManger.setKeyWordData(keyWordData);
                searchManger.setWebSiteData(webSiteData);
                searchManger.setWebSiteStopTime(webSiteStopTime);
                searchManger.setTaskLoopNum(taskLoopNum);
                searchManger.setNowTaskLoopNum(nowTaskLoopNum);
                searchManger.setLoadKeyWordData(loadkeyWordData);
                searchManger.setLoadWebSiteData(loadwebSiteData);
            }

        }
        return searchManger;
    }

    public static Context getContext() {
        return context;
    }

    public void openBrowser() {
        Intent i = new Intent();
        i.setPackage(context.getResources().getString(R.string.browser_app_package_name));
        i.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("https://www.baidu.com");
        i.setData(content_url);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }


    public int getTaskLoopNum() {
        return taskLoopNum;
    }

    public void setTaskLoopNum(int taskLoopNum) {
        this.taskLoopNum = taskLoopNum;
    }

    public int getNowTaskLoopNum() {
        return nowTaskLoopNum;
    }

    public void setNowTaskLoopNum(int nowTaskLoopNum) {
        this.nowTaskLoopNum = nowTaskLoopNum;
    }


    public AccessibilityNodeInfo getBtn_search() {
        return btn_search;
    }

    public AccessibilityNodeInfo getEdit_search() {
        return edit_search;
    }

    public List<AccessibilityNodeInfo> getContentMatchList() {
        return contentMatchList;
    }


    public List<KeyWordBean> getKeyWordData() {
        return keyWordData;
    }

    public void setKeyWordData(List<KeyWordBean> keyWordData) {
        this.keyWordData = keyWordData;
        if(loadKeyWordData==null)
        {
            loadKeyWordData=new ArrayList<>();
            for(KeyWordBean keyWordBean:keyWordData)
            {
                loadKeyWordData.add(keyWordBean);
            }
        }
    }

    public List<WebSiteBean> getWebSiteData() {
        return webSiteData;
    }

    public void setWebSiteData(List<WebSiteBean> webSiteData) {
        
        this.webSiteData = webSiteData;
        if(loadWebSiteData==null)
        {
            loadWebSiteData=new ArrayList<>();
            for(WebSiteBean webSiteBean:webSiteData)
            {
                loadWebSiteData.add(webSiteBean);
            }
        }
    }

    public int getWebSiteStopTime() {
        return webSiteStopTime;
    }

    public void setWebSiteStopTime(int webSiteStopTime) {
        this.webSiteStopTime = webSiteStopTime;
    }

    public boolean searchBaiduMainSearchView(AccessibilityNodeInfo nodeInfo) {
        return recycleSearchBaiduMainSearchView(nodeInfo);
    }

    public boolean searchBaiduMainBtnSearchView(AccessibilityNodeInfo nodeInfo) {
        return recycleSearchBaiduMainBtnSearchView(nodeInfo);
    }


    public void checkIsSearchMain(AccessibilityNodeInfo info) {
        boolean isHaveText = (info.getText() != null && info.getText().toString().equals("百度一下")) || (info.getContentDescription() != null && info.getContentDescription().toString().equals("百度一下"));
        if (info.getViewIdResourceName() != null && isHaveText && info.getClassName().equals("android.widget.Button")) {
            recycleIsSearchMain(info);
            if(btn_search!=null)
            {
                isMain=true;
            }
        }
    }

    public Boolean[] mainKey = {false, false, false, false, false};
    public boolean isMain = false;

    public void recycleIsSearchMainold(AccessibilityNodeInfo info) {

        boolean isHaveText = (info.getText() != null && info.getText().toString().equals("百度一下"))
                || (info.getContentDescription() != null && info.getContentDescription().toString().equals("百度一下"));
        if (info.getViewIdResourceName() == null && info.getClassName().equals("android.view.View")) {
            String text = "";
            if (info.getText() != null) {
                text = info.getText().toString();
            } else if (info.getContentDescription() != null) {
                text = info.getContentDescription().toString();
            }

            if (text.equals("关注")) {

                mainKey[0] = true;
            } else if (text.equals(" 新闻")) {

                mainKey[1] = true;
            } else if (text.equals("小说")) {

                mainKey[2] = true;
            } else if (text.equals("视频")) {

                mainKey[3] = true;
            }
        } else if (info.getViewIdResourceName() != null && isHaveText
                && info.getClassName().equals("android.widget.Button")) {

            btn_search = info;
            mainKey[4] = true;
        }

    }

    /**
     * 首页检测新逻辑
     * @param info
     */
    public void recycleIsSearchMain(AccessibilityNodeInfo info) {

        boolean isHaveText = (info.getText() != null && info.getText().toString().equals("百度一下"))
                || (info.getContentDescription() != null && info.getContentDescription().toString().equals("百度一下"));
         if (info.getViewIdResourceName() != null && isHaveText
                && info.getClassName().equals("android.widget.Button")) {
            btn_search = info;
        }

    }


    public boolean editSearchContent(AccessibilityNodeInfo info) {

        if (info.getClassName().equals("android.widget.EditText") && info.getViewIdResourceName() != null && info.getViewIdResourceName().equals("index-kw")) {
            edit_search = info;
            String nextKeyWord = getNextKeyWord();
            if (SearchBaiduInfoReceiver.setSearchContent(edit_search, nextKeyWord)) {
                String text="";
                boolean b = btn_search.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.e(TAG, "主页搜索按钮点击结果:" + b);
                if(!b)
                {
                    CommandManger manger = CommandManger.getManger();
                    manger.getCommandQueue().clear();
                    manger.loadBrowserCommand(SearchManger.getContext(),true);
                    return true;
                }
                return b;
            }

        }
        return false;
    }


    public boolean recycleSearchBaiduMainSearchView(AccessibilityNodeInfo info) {
        if (info.getClassName().equals("android.widget.EditText") && info.getViewIdResourceName() != null && info.getViewIdResourceName().equals("kw")) {
            edit_search = info;
            Log.i(TAG, edit_search.toString());
            return true;
        }
        return false;
    }

    public boolean recycleSearchBaiduMainBtnSearchView(AccessibilityNodeInfo info) {
        boolean isHaveText = (info.getText() != null && info.getText().toString().equals("百度一下"))
                || (info.getContentDescription() != null && info.getContentDescription().toString().equals("百度一下"));
        if (info.getClassName().equals("android.widget.Button") && info.getViewIdResourceName() != null && info.getViewIdResourceName().equals("se-bn")
                && isHaveText) {
            btn_search = info;
            Log.i(TAG, btn_search.toString());
            return true;
        }
        return false;
    }


    /***
     * 匹配网页数据与网站库单词  匹配数
     * @param info
     * @return
     */
    public synchronized void recycleSearchWebSiteInKeyWordReslutCount(AccessibilityNodeInfo info) {
        boolean isHaveText = (info.getText() != null || info.getContentDescription() != null);

        if (info.getClassName().equals("android.view.View") && info.getViewIdResourceName() == null
                && isHaveText && info.isClickable()) {
            String text = "";
            if (info.getText() != null) {
                text = info.getText().toString();
            } else if (info.getContentDescription() != null) {
                text = info.getContentDescription().toString();
            }
            if (text.equals("")) return;
            if (text.length() > 20 || text.charAt(text.length() - 1) == '.') return;
            for (WebSiteBean webSiteBean : webSiteData) {
                boolean isContains = false;
                String webSiteString = webSiteBean.getWebSiteString();
                if (text.length() > webSiteString.length()) {
                    isContains = text.contains(webSiteString);
                } else {
                    isContains = webSiteString.contains(text);
                }
                for (AccessibilityNodeInfo nodeInfo : contentMatchList) {
                    String t = "";
                    if (info.getText() != null) {
                        t = nodeInfo.getText().toString();
                    } else if (info.getContentDescription() != null) {
                        t = nodeInfo.getContentDescription().toString();
                    }
                    boolean equals = t.equals(text);
                    if (equals) {
                        return;
                    }
                }

                for (AccessibilityNodeInfo nodeInfo : oldContentMatchList) {
                    String t = "";
                    if (info.getText() != null) {
                        t = nodeInfo.getText().toString();
                    } else if (info.getContentDescription() != null) {
                        t = nodeInfo.getContentDescription().toString();
                    }
                    boolean equals = t.equals(text);
                    if (equals) {
                        return;
                    }
                }
                if (isContains && !text.equals("")) {
                    contentMatchList.add(info);
                    return;
                }
            }
        }
        return;
    }
    
    /***
     * 单个开始匹配
     * @param info
     * @return
     */
    public AccessibilityNodeInfo nowClickString = null;
    public boolean isNotMatch = false;

    public synchronized boolean recycleSearchWebSiteInKeyWordReslut(AccessibilityNodeInfo info) {
        boolean isHaveText = (info.getText() != null || info.getContentDescription() != null);

        if (info.getClassName().equals("android.view.View") && info.getViewIdResourceName() == null
                && isHaveText && info.isClickable()) {
            String text = "";
            if (info.getText() != null) {
                text = info.getText().toString();
            } else if (info.getContentDescription() != null) {
                text = info.getContentDescription().toString();
            }

            if (text.equals("")) return false;
            if (text.length() > 20 || text.charAt(text.length() - 1) == '.') return false;

            if (contentMatchList.size() == 0) {
                isNotMatch = true;
                return false;
            }
            for (int i = 0; i < contentMatchList.size(); i++) {
                AccessibilityNodeInfo nodeInfo = contentMatchList.get(i);
                String t = "";
                if (info.getText() != null) {
                    t = nodeInfo.getText().toString();
                } else if (info.getContentDescription() != null) {
                    t = nodeInfo.getContentDescription().toString();
                }
                boolean equals = t.equals(text);
                if (equals) {
                    nowClickString = info;
                    oldContentMatchList.add(info);
                    return true;
                }

            }

        }
        return false;
    }
    
    int count=0;
    public boolean checkMatchWebSiteIsLoaded(AccessibilityNodeInfo info)
    {
        if(info.getClassName()!=null && info.getClassName().equals("android.webkit.WebView"))
        {
             recycleWebViewAllCount(info);
             if(isBaiDuWeb)
             {
                 count=0;
                 isBaiDuWeb=false;
             }
             //当webView下子元素大于5个时认为已经匹配页面加载完成
             if(count>5)
             {
                 return true;
             }
            count=0;
        }
        return false;
        
    }
    
    private boolean isBaiDuWeb=false;
    public void recycleWebViewAllCount(AccessibilityNodeInfo info)
    {
        if(info.getChildCount()==0)
        {
            //过滤延迟时会扫描到百度搜索页的信息
            boolean isHaveText = (info.getText() != null && info.getText().toString().equals("百度一下"))
                    || (info.getContentDescription() != null && info.getContentDescription().toString().equals("百度一下"));
            if (info.getClassName().equals("android.widget.Button") && info.getViewIdResourceName() != null && info.getViewIdResourceName().equals("se-bn")
                    && isHaveText) {
                isBaiDuWeb=true;
            }
            count++;
        }else
        {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycleWebViewAllCount(info.getChild(i));
                }
            }
        }
    }


    public boolean performActionClick(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) return false;
        boolean clickReslut = nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

        if (clickReslut) return true;
        return false;
    }

    private AccessibilityNodeInfo operaMenuButtonInfo = null;
    private AccessibilityNodeInfo operaReloadButton = null;
    private AccessibilityNodeInfo morePageButtonInfo = null;
    private AccessibilityNodeInfo closeAllBtuutonInfo = null;

    public AccessibilityNodeInfo getOperaMenuButtonInfo() {
        return operaMenuButtonInfo;
    }

    public void setOperaMenuButtonInfo(AccessibilityNodeInfo operaMenuButtonInfo) {
        this.operaMenuButtonInfo = operaMenuButtonInfo;
    }

    public AccessibilityNodeInfo getOperaReloadButton() {
        return operaReloadButton;
    }

    public void setOperaReloadButton(AccessibilityNodeInfo operaReloadButton) {
        this.operaReloadButton = operaReloadButton;
    }

    public AccessibilityNodeInfo getMorePageButtonInfo() {
        return morePageButtonInfo;
    }

    public void setMorePageButtonInfo(AccessibilityNodeInfo morePageButtonInfo) {
        this.morePageButtonInfo = morePageButtonInfo;
    }

    public AccessibilityNodeInfo getCloseAllBtuutonInfo() {
        return closeAllBtuutonInfo;
    }

    public void setCloseAllBtuutonInfo(AccessibilityNodeInfo closeAllBtuutonInfo) {
        this.closeAllBtuutonInfo = closeAllBtuutonInfo;
    }

    public void searchOperaMenuButtonInfo(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo.getClassName() != null && nodeInfo.getClassName().equals("android.widget.ImageView") && nodeInfo.getViewIdResourceName() != null
                && nodeInfo.getViewIdResourceName().contains("bottom_navigation_bar_opera_menu_button")) {
            operaMenuButtonInfo = nodeInfo;
        }
    }

    public void searchoperaReloadButtonInfo(AccessibilityNodeInfo nodeInfo) {

        if (nodeInfo.getClassName() != null && nodeInfo.getClassName().equals("android.widget.TextView") && nodeInfo.getViewIdResourceName() != null
                && nodeInfo.getViewIdResourceName().contains("function_menu_reload_button")) {
            operaReloadButton = nodeInfo;
        }
    }


    public void searchMorePageButtonInfo(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo.getClassName() != null && nodeInfo.getClassName().equals("android.widget.ImageView") && nodeInfo.getContentDescription() != null
                && nodeInfo.getContentDescription().equals("打开标签")) {
            morePageButtonInfo = nodeInfo.getParent();
        }
    }

    public void searchCloseAllBtuutonInfo(AccessibilityNodeInfo nodeInfo) {

        if (nodeInfo.getClassName() != null && nodeInfo.getClassName().equals("android.widget.ImageView") && nodeInfo.getViewIdResourceName() != null
                && nodeInfo.getViewIdResourceName().contains("tab_menu_toolbar_close_all")) {
            closeAllBtuutonInfo = nodeInfo;
        }
    }

    /**
     * 打开唤醒辅助功能弹窗
     * @param type
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void jumpActivationActivity(String type) {
        if(type.equals(OPEN_WAKE_WINWODS)) {
            SystemALertDialog dialog = new SystemALertDialog(context);
            dialog.show();
        }
    }


    /***
     * 获取当前的关键字
     * @return
     */
    public String getNextKeyWord() {
        if (keyWordData != null && keyWordData.size() > 0) {
            String keyWordString = keyWordData.get(0).getKeyWordString();
//            keyWordData.remove(0);
            return keyWordString;
        }
        return "";
    }
    /***
     * 当该关键词的所有匹配项全部检索完成后，移除这个关键词，进行下一个关键词的匹配
     * @return
     */
    public boolean removeNowKeyWord() {
        if (keyWordData != null && keyWordData.size() > 0) {
            keyWordData.remove(0);
            if (keyWordData.size() == 0) return false;
            return true;
        }
        return false;
    }

    public List<KeyWordBean> getLoadKeyWordData() {
        return loadKeyWordData;
    }

    public void setLoadKeyWordData(List<KeyWordBean> loadKeyWordData) {
        this.loadKeyWordData = loadKeyWordData;
    }

    public List<WebSiteBean> getLoadWebSiteData() {
        return loadWebSiteData;
    }

    public void setLoadWebSiteData(List<WebSiteBean> loadWebSiteData) {
        this.loadWebSiteData = loadWebSiteData;
    }

    public static void ClearManger()
    {
        searchManger=null;
    }
}
